package com.ctvit.cch.core.task;

import com.ctvit.cch.core.service.IHotRecordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

/**
 * 热榜记录聚合评分更新任务
 *
 * @author heyingcheng
 * @date 2025/11/15
 */
@Slf4j
@Component("aggregateScoreTask")
@ConditionalOnProperty(name = "cch.core.task.aggregate-score.enabled", havingValue = "true")
public class AggregateScoreTask implements SchedulingConfigurer {

    // 每30分钟执行一次
    private static final String CRON_EXPRESSION = "0 0/30 * * * ?";

    @Resource
    private IHotRecordService hotRecordService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(this::execute, triggerContext -> {
            CronTrigger trigger = new CronTrigger(CRON_EXPRESSION);
            return trigger.nextExecution(triggerContext);
        });
    }

    public void execute() {
        log.debug("执行热榜记录聚合评分更新任务-开始");
        try {
            int updatedCount = hotRecordService.aggregate(30);
            log.debug("执行热榜记录聚合评分更新任务-结束，共更新了[{}]条记录", updatedCount);
        } catch (Exception e) {
            log.error("执行热榜记录聚合评分更新任务异常", e);
        }
    }

}
